package com.leo.foodmaster.commons.config.security;

import cn.hutool.core.util.StrUtil;
import com.leo.foodmaster.admin.system.entity.UserBean;
import com.leo.foodmaster.commons.constants.AuthConstants;
import com.leo.foodmaster.commons.util.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;

/**
 * <p>
 * token过滤器 验证token有效性
 * </p>
 *
 * @author ：Leo
 * @since ：2021-06-19 8:47
 */
@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Resource
    private TokenUtils tokenUtils;

    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request,
                                    @NonNull HttpServletResponse response,
                                    @NonNull FilterChain chain) throws ServletException, IOException {
        String token = tokenUtils.getToken(request);
        // 一、如果token为空则直接放行
        if (StrUtil.isBlank(token)) {
            chain.doFilter(request, response);
            return;
        }

        // 二、校验token是否有效
        tokenUtils.validateToken(token);

        // 三、将用户信息存入请求头中
        UserBean user = tokenUtils.getLoginUserFromToken(token);
        request.setAttribute(AuthConstants.USER_INFO, user);

        // 四、将authentication信息放入到上下文目标中
        Collection<GrantedAuthority> authorities = tokenUtils.getAuthoritiesFromToken(token);
        UsernamePasswordAuthenticationToken authentication =
                new UsernamePasswordAuthenticationToken(user.getName(), null, authorities);
        SecurityContextHolder.getContext().setAuthentication(authentication);

        chain.doFilter(request, response);
    }
}
